<template>
  <div class="user-manage">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">用户管理</span>
          <div class="actions">
            <el-input
            v-model="searchKeyword"
            placeholder="搜索用户名或手机号"
            style="width: 300px"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch">
            <template #append>
              <el-button :icon="Search" @click="handleSearch" />
            </template>
            </el-input>
            <el-button type="success" @click="openAddDialog" style="margin-left: 10px">新增用户</el-button>
          </div>
        </div>
      </template>

      <!-- 用户列表表格 -->
      <el-table :data="userList" v-loading="loading" stripe>
        <el-table-column prop="id" label="用户ID" width="200" />
        <el-table-column prop="username" label="用户名" width="150" />
        <el-table-column prop="phone" label="手机号" width="150" />
        <el-table-column prop="balance" label="余额" width="120">
          <template #default="{ row }">
            <span style="color: #f56c6c">¥{{ row.balance.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="is_admin" label="角色" width="100">
          <template #default="{ row }">
            <el-tag :type="row.is_admin ? 'danger' : 'info'">
              {{ row.is_admin ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleUpdateBalance(row)">
              调整余额
            </el-button>
            <el-button type="warning" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button 
              v-if="!row.is_admin"
              type="danger" 
              size="small" 
              @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="fetchUsers"
        @current-change="fetchUsers"
        style="margin-top: 20px; justify-content: center"
      />
    </el-card>

    <!-- 调整余额对话框 -->
    <el-dialog v-model="balanceDialogVisible" title="调整用户余额" width="500px">
      <el-form :model="balanceForm" label-width="100px">
        <el-form-item label="用户名">
          <span>{{ balanceForm.username }}</span>
        </el-form-item>
        <el-form-item label="手机号">
          <span>{{ balanceForm.phone }}</span>
        </el-form-item>
        <el-form-item label="当前余额">
          <span style="color: #f56c6c; font-weight: bold">
            ¥{{ balanceForm.currentBalance.toFixed(2) }}
          </span>
        </el-form-item>
        <el-form-item label="调整金额">
          <el-input-number
            v-model="balanceForm.amount"
            :precision="2"
            :step="10"
            :min="-10000"
            :max="10000"
            style="width: 100%"
          />
          <div style="color: #909399; font-size: 12px; margin-top: 5px">
            正数为充值，负数为扣款
          </div>
        </el-form-item>
        <el-form-item label="调整后余额">
          <span style="color: #67c23a; font-weight: bold">
            ¥{{ (balanceForm.currentBalance + balanceForm.amount).toFixed(2) }}
          </span>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="balanceDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmUpdateBalance">确认调整</el-button>
      </template>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑用户信息" width="500px">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="用户ID">
          <span>{{ editForm.userId }}</span>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="editForm.phone" placeholder="请输入手机号" maxlength="11" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmEdit">确认修改</el-button>
      </template>
    </el-dialog>

    <!-- 新增用户对话框 -->
    <el-dialog v-model="addDialogVisible" title="新增用户" width="500px">
      <el-form :model="addForm" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="addForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="addForm.phone" placeholder="请输入手机号" maxlength="11" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="addForm.password" type="password" placeholder="请输入密码（8-20位）" />
        </el-form-item>
        <el-form-item label="角色">
          <el-switch v-model="addForm.is_admin" active-text="管理员" inactive-text="普通用户" />
        </el-form-item>
        <el-form-item label="初始余额">
          <el-input-number v-model="addForm.balance" :precision="2" :step="10" :min="0" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAdd">确认新增</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { adminApis } from '@/assets/apis/AdminApis'

// 数据
const loading = ref(false)
const userList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchKeyword = ref('')

// 余额调整
const balanceDialogVisible = ref(false)
const balanceForm = ref({
  userId: 0,
  username: '',
  phone: '',
  currentBalance: 0,
  amount: 0
})

// 编辑用户
const editDialogVisible = ref(false)
const editForm = ref({
  userId: '',
  username: '',
  phone: ''
})

// 新增用户
const addDialogVisible = ref(false)
const addForm = ref({
  username: '',
  phone: '',
  password: '',
  is_admin: false,
  balance: 0
})

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true
  try {
    const data = await adminApis.getUsers(
      currentPage.value,
      pageSize.value,
      searchKeyword.value
    )
    userList.value = data.users
    total.value = data.total
  } catch (error: any) {
    console.error('获取用户列表失败：', error)
    ElMessage.error(error.error || '获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchUsers()
}

// 打开调整余额对话框
const handleUpdateBalance = (row: any) => {
  balanceForm.value = {
    userId: row.id,
    username: row.username,
    phone: row.phone,
    currentBalance: row.balance,
    amount: 0
  }
  balanceDialogVisible.value = true
}

// 确认调整余额
const confirmUpdateBalance = async () => {
  if (balanceForm.value.amount === 0) {
    ElMessage.warning('请输入调整金额')
    return
  }

  try {
    await adminApis.updateUserBalance(
      balanceForm.value.userId,
      balanceForm.value.amount
    )
    ElMessage.success('余额调整成功')
    balanceDialogVisible.value = false
    fetchUsers()
  } catch (error: any) {
    console.error('调整余额失败：', error)
    ElMessage.error(error.error || '调整余额失败')
  }
}

// 打开编辑对话框
const handleEdit = (row: any) => {
  editForm.value = {
    userId: row.id,
    username: row.username,
    phone: row.phone
  }
  editDialogVisible.value = true
}

// 确认编辑
const confirmEdit = async () => {
  if (!editForm.value.username.trim()) {
    ElMessage.warning('请输入用户名')
    return
  }
  if (!editForm.value.phone.trim()) {
    ElMessage.warning('请输入手机号')
    return
  }

  try {
    await adminApis.updateUser(
      editForm.value.userId,
      editForm.value.username,
      editForm.value.phone
    )
    ElMessage.success('用户信息更新成功')
    editDialogVisible.value = false
    fetchUsers()
  } catch (error: any) {
    console.error('更新用户失败：', error)
    ElMessage.error(error.error || '更新失败')
  }
}

// 打开新增用户对话框
const openAddDialog = () => {
  addForm.value = {
    username: '',
    phone: '',
    password: '',
    is_admin: false,
    balance: 0
  }
  addDialogVisible.value = true
}

// 确认新增用户
const confirmAdd = async () => {
  if (!addForm.value.username.trim()) {
    ElMessage.warning('请输入用户名')
    return
  }
  if (!addForm.value.phone.trim() || !/^\d{11}$/.test(addForm.value.phone)) {
    ElMessage.warning('请输入正确的手机号（11位数字）')
    return
  }
  if (!addForm.value.password.trim() || addForm.value.password.length < 8 || addForm.value.password.length > 20) {
    ElMessage.warning('请输入8-20位的密码')
    return
  }

  try {
    await adminApis.createUser(
      addForm.value.username,
      addForm.value.phone,
      addForm.value.password,
      addForm.value.is_admin,
      addForm.value.balance
    )
    ElMessage.success('用户新增成功')
    addDialogVisible.value = false
    fetchUsers()
  } catch (error: any) {
    console.error('新增用户失败：', error)
    ElMessage.error(error.error || '新增用户失败')
  }
}

// 删除用户
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定删除用户"${row.username}"吗？删除后将无法恢复！`,
    '警告',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await adminApis.deleteUser(row.id)
      ElMessage.success('用户删除成功')
      fetchUsers()
    } catch (error: any) {
      console.error('删除用户失败：', error)
      ElMessage.error(error.error || '删除失败')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 初始化
onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.user-manage {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.actions {
  display: flex;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}
</style>

